const express = require('express');
const router = express.Router();
const db = require('../database/db');

// 获取所有自定义接口
router.get('/custom-apis', async (req, res) => {
  try {
    const apis = await db.getAllApis();
    // 获取每个接口的参数信息
    const apisWithParams = await Promise.all(apis.map(async (api) => {
      const parameters = await db.getApiParameters(api.id);
      const inputParam = parameters.find(p => p.param_type === 'input');
      const outputParam = parameters.find(p => p.param_type === 'output');
      return {
        ...api,
        inputSchema: inputParam ? inputParam.param_schema : '',
        outputSchema: outputParam ? outputParam.param_schema : ''
      };
    }));
    res.json(apisWithParams);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 创建新接口
router.post('/custom-apis', async (req, res) => {
  try {
    const { name, description, inputSchema, outputSchema } = req.body;
    console.log(inputSchema);
    console.log(outputSchema);
    const apiId = await db.createApi(name, description);
    
    if (inputSchema) {
      await db.createParameter(apiId, 'input', 'input', inputSchema);
    }
    if (outputSchema) {
      await db.createParameter(apiId, 'output', 'output', outputSchema);
    }
    
    res.json({ id: apiId });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新接口
router.put('/custom-apis/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, description, inputSchema, outputSchema } = req.body;
    
    // 更新基本信息
    await db.updateApi(id, name, description);
    
    // 更新输入参数
    if (inputSchema) {
      await db.updateParameter(id, 'input', 'input', inputSchema);
    }
    
    // 更新输出参数
    if (outputSchema) {
      await db.updateParameter(id, 'output', 'output', outputSchema);
    }
    
    // 返回更新后的完整数据
    const updatedApi = {
      id,
      name,
      description,
      inputSchema,
      outputSchema
    };
    
    res.json(updatedApi);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除接口
router.delete('/custom-apis/:id', async (req, res) => {
  try {
    const { id } = req.params;
    await db.deleteApi(id);
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 添加获取单个接口详情的路由
router.get('/custom-apis/:id', async (req, res) => {
  try {
    const { id } = req.params;
    console.log('Fetching API details for ID:', id); // 添加日志

    const api = await db.getApiById(id);
    console.log('Found API:', api); // 添加日志

    if (!api) {
      console.log('API not found'); // 添加日志
      return res.status(404).json({ error: 'API not found' });
    }

    // 获取参数信息
    const parameters = await db.getApiParameters(id);
    console.log('Found parameters:', parameters); // 添加日志

    const inputParam = parameters.find(p => p.param_type === 'input');
    const outputParam = parameters.find(p => p.param_type === 'output');

    const apiWithParams = {
      ...api,
      inputSchema: inputParam ? inputParam.param_schema : '',
      outputSchema: outputParam ? outputParam.param_schema : ''
    };

    console.log('Sending response:', apiWithParams); // 添加日志
    res.json(apiWithParams);
  } catch (error) {
    console.error('Error in GET /custom-apis/:id:', error); // 添加错误日志
    res.status(500).json({ error: error.message });
  }
});

module.exports = router; 